/*
 * AgencyView.java
 *
 * Created on December 11, 2008, 12:29 PM
 */

package researchgrants.parts.GrantRequest.agency;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.SortedMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import researchgrants.parts.LoggedData.HistoricallyLoggedData;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsText;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import researchgrants.parts.LoggedData.panels.lists.LoggedDataPanelsList;
import researchgrants.parts.db.Db;
import researchgrants.parts.panelsManager.LoggedDataPanelsManager;
import researchgrants.utils.MyDialog;

/**
 * Displays an existing Agency or inputs a new Agency, depends on the constructor called
 * @author  DOStudent1
 */
public class AgencyView extends MyDialog {
    private static final int hgap=0;

    // the agency involved
    private Agency agency;
    // a flag whether it is a new agency or an existing one
    private boolean isNewAgency;

    // the different elements
    private LoggedDataPanelsManager agencyNameView;
    private LoggedDataPanelsManager agencyCategoryView;
    private LoggedDataPanelsManager notesView;
    
    // global components
    private JButton btnSaveAll;
    private JPanel pnlWarnings=new JPanel();

    
    //inputs a new agency 
    AgencyView(Window parent) {
        super(parent);
        isNewAgency=true;
        initComponents();
        initDisplay();
    }

    //shows an existing agency
    AgencyView(Window parent, Agency agency) {
        super(parent);
        this.agency=agency;
        isNewAgency=false;
        initComponents();
        initDisplay();
    }

    // Saves a new Agency from the fields
    private void createNewAgencyFromFields() {
        try {

            Connection conn=Db.openDbConnection();
            PreparedStatement createAgencyStatement = Db.createPreparedStatement(conn, "INSERT INTO tblAgencies (AgencyNameRef, AgencyCategoryIDRef, NotesRef) VALUES (?, ?, ?)");

            
            ////////////////////////////////////
            // Save all different data pieces
            ////////////////////////////////////
            
            createAgencyStatement.setInt(1, saveLoggedDataPanelsManagerData(agencyNameView));
            createAgencyStatement.setInt(2, saveLoggedDataPanelsManagerData(agencyCategoryView));
            createAgencyStatement.setInt(3, saveLoggedDataPanelsManagerData(notesView));

            
            // Saves the agency
            createAgencyStatement.executeUpdate();

            int newAgencyId = Db.getLastIdentity();
            createAgencyStatement.close();
            Db.closeDbConnection(conn);

            // retrieves the newly saved data
            this.agency=Agency.getById(newAgencyId);
            
            //setVisible(false);
            
        } catch (SQLException ex) {
            Logger.getLogger(AgencyView.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // refreshes the display to an existing Agency
        isNewAgency=false;
        initDisplay();
    }
    
    // Re/displays the Agency
    private void initDisplay() {
        // the save button
        if (isNewAgency) {
            btnSaveAll=new JButton("Save New Agency Contact");
            btnSaveAll.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    createNewAgencyFromFields();
                }

            });
        }

        
        if (isNewAgency) {
            lblId.setText("<Auto>");
        } else {
            lblId.setText(Integer.toString(agency.getId()));
        }

        ///////////////////////////////////////
        // adds all the internal data's views
        ///////////////////////////////////////

        HistoricallyLoggedData agencyName=null;
        HistoricallyLoggedData agencyCategoryID=null;
        HistoricallyLoggedData notes=null;

        if (!isNewAgency) {
            agencyName=agency.getAngecyName();
            agencyCategoryID=agency.getAgencyCategoryId();
            notes=agency.getAgencyNotes();
        }
        
        agencyNameView=createLoggedDataPanelManager(false, isNewAgency, new LoggedDataPanelsText(),this, agencyName, pnlFieldName);
        {
            LoggedDataPanelsListAgencyCategory panels=new LoggedDataPanelsListAgencyCategory();
            ChangeListener changeEventListener = new AgencyCategoryChangeListener(panels);
            agencyCategoryView=createLoggedDataPanelManager(true, isNewAgency, panels, this, agencyCategoryID, pnlFieldAgencyCategory, changeEventListener);
        }
        notesView=createLoggedDataPanelManager(false, isNewAgency, new LoggedDataPanelsTextArea(),this, notes, pnlFieldNotes);


        //////////////////////
        // The buttons
        //////////////////////
        
        JPanel pnlOptionalButtonsInner=new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        pnlOptionalButtonsInner.setLayout(new GridLayout());
        
        boolean displayButtonsPanel=false;
        // only if the AgencyContact is new, allow to save the initial data
        if (isNewAgency) {
            JPanel pnlOptionalButtonsInner2=new JPanel(new BorderLayout(0, 0));
            pnlOptionalButtonsInner2.add(pnlWarnings, BorderLayout.NORTH);
            pnlOptionalButtonsInner2.add(btnSaveAll, BorderLayout.CENTER);
            pnlOptionalButtonsInner.add(pnlOptionalButtonsInner2);
            displayButtonsPanel=true;
        }
        
        pnlOptionalButtons.removeAll();
        // if no buttons, remove panel
        if (displayButtonsPanel) {
                pnlOptionalButtons.add(wrapSection(pnlOptionalButtonsInner, "Options"));
        }
        
        validateEntireForm();
        pack();
        setLocationRelativeTo(getParent());
        setVisible(true);

    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlID = new javax.swing.JPanel();
        lblCaptionId = new javax.swing.JLabel();
        lblId = new javax.swing.JLabel();
        pnlName = new javax.swing.JPanel();
        lblCaptionName = new javax.swing.JLabel();
        pnlFieldName = new javax.swing.JPanel();
        pnlAgencyCategory = new javax.swing.JPanel();
        lblCaptionAgencyCategory = new javax.swing.JLabel();
        pnlFieldAgencyCategory = new javax.swing.JPanel();
        pnlNotes = new javax.swing.JPanel();
        lblCaptionNotes = new javax.swing.JLabel();
        pnlFieldNotes = new javax.swing.JPanel();
        pnlOptionalButtons = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(researchgrants.ResearchGrantsApp.class).getContext().getResourceMap(AgencyView.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        pnlID.setName("pnlID"); // NOI18N
        pnlID.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionId.setText(resourceMap.getString("lblCaptionId.text")); // NOI18N
        lblCaptionId.setName("lblCaptionId"); // NOI18N
        pnlID.add(lblCaptionId);

        lblId.setText(resourceMap.getString("lblId.text")); // NOI18N
        lblId.setName("lblId"); // NOI18N
        pnlID.add(lblId);

        getContentPane().add(pnlID);

        pnlName.setName("pnlName"); // NOI18N
        pnlName.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionName.setText(resourceMap.getString("lblCaptionName.text")); // NOI18N
        lblCaptionName.setName("lblCaptionName"); // NOI18N
        pnlName.add(lblCaptionName);

        pnlFieldName.setName("pnlFieldName"); // NOI18N
        pnlFieldName.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlName.add(pnlFieldName);

        getContentPane().add(pnlName);

        pnlAgencyCategory.setName("pnlAgencyCategory"); // NOI18N
        pnlAgencyCategory.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionAgencyCategory.setText(resourceMap.getString("lblCaptionAgencyCategory.text")); // NOI18N
        lblCaptionAgencyCategory.setName("lblCaptionAgencyCategory"); // NOI18N
        pnlAgencyCategory.add(lblCaptionAgencyCategory);

        pnlFieldAgencyCategory.setName("pnlFieldAgencyCategory"); // NOI18N
        pnlFieldAgencyCategory.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlAgencyCategory.add(pnlFieldAgencyCategory);

        getContentPane().add(pnlAgencyCategory);

        pnlNotes.setName("pnlNotes"); // NOI18N
        pnlNotes.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionNotes.setText(resourceMap.getString("lblCaptionNotes.text")); // NOI18N
        lblCaptionNotes.setName("lblCaptionNotes"); // NOI18N
        pnlNotes.add(lblCaptionNotes);

        pnlFieldNotes.setName("pnlFieldNotes"); // NOI18N
        pnlFieldNotes.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlNotes.add(pnlFieldNotes);

        getContentPane().add(pnlNotes);

        pnlOptionalButtons.setName("pnlOptionalButtons"); // NOI18N
        pnlOptionalButtons.setLayout(new javax.swing.BoxLayout(pnlOptionalButtons, javax.swing.BoxLayout.LINE_AXIS));
        getContentPane().add(pnlOptionalButtons);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblCaptionAgencyCategory;
    private javax.swing.JLabel lblCaptionId;
    private javax.swing.JLabel lblCaptionName;
    private javax.swing.JLabel lblCaptionNotes;
    private javax.swing.JLabel lblId;
    private javax.swing.JPanel pnlAgencyCategory;
    private javax.swing.JPanel pnlFieldAgencyCategory;
    private javax.swing.JPanel pnlFieldName;
    private javax.swing.JPanel pnlFieldNotes;
    private javax.swing.JPanel pnlID;
    private javax.swing.JPanel pnlName;
    private javax.swing.JPanel pnlNotes;
    private javax.swing.JPanel pnlOptionalButtons;
    // End of variables declaration//GEN-END:variables

    // a panel of a list of all agencies
    private static class LoggedDataPanelsListAgencyCategory extends LoggedDataPanelsList {

        public SortedMap<String, String> getListMap() {
            SortedMap<String, String> agencyCategories=null;
            try {
                Connection conn=Db.openDbConnection();
                PreparedStatement prepareStatement = Db.createPreparedStatement(conn, "SELECT AgencyCategoryID, cstr(AgencyCategoryID) + ' (' + AgencyCategoryText + ')' FROM tblAgencyCategories ORDER BY AgencyCategoryID");
                ResultSet agencyCategoriesResultSet = prepareStatement.executeQuery();
                agencyCategories = Db.getMap(agencyCategoriesResultSet);
                agencyCategoriesResultSet.close();
                prepareStatement.close();
                Db.closeDbConnection(conn);
            } catch (SQLException ex) {
                Logger.getLogger(LoggedDataPanelsListAgencyCategory.class.getName()).log(Level.SEVERE, null, ex);
            }
            return agencyCategories;
        }
    }

    /////////////////////////
    // Validates the form
    /////////////////////////
    
    // each individual component is validates/invalidates seperately, using its designated Listener
    // the entire form is revalidated after any idnividual change
    
    private boolean isAgencyCategoryValid=false;
    
    private void validateEntireForm() {
        setSaveEnabled(isAgencyCategoryValid);
        pnlWarnings.removeAll();
        int warnings=0;
        if (!isAgencyCategoryValid) {
            JLabel lblWarning=new JLabel("You must select an Agency Category");
            lblWarning.setForeground(Color.RED);
            pnlWarnings.add(lblWarning);
            warnings++;
        }

        pnlWarnings.setLayout(new GridLayout(warnings, 1));
        pnlWarnings.revalidate();
    }
    
    private class AgencyCategoryChangeListener implements ChangeListener {
        LoggedDataPanelsListAgencyCategory loggedDataPanelsAgencyCategory;

        public AgencyCategoryChangeListener(LoggedDataPanelsListAgencyCategory loggedDataPanelsAgencyCategory) {
            this.loggedDataPanelsAgencyCategory = loggedDataPanelsAgencyCategory;
        }

        public void stateChanged(ChangeEvent e) {
            isAgencyCategoryValid=((loggedDataPanelsAgencyCategory.isValid()) && (!loggedDataPanelsAgencyCategory.isEmpty()));
            validateEntireForm();
        }
    }

    private void setSaveEnabled(boolean enabled) {
        // will only be used when a global save button is availalbe
        if (btnSaveAll!=null) {
            btnSaveAll.setEnabled(enabled);
        }
    }


    // Returns the Agency. Useful to retreive a newly saved Agency
    public Agency getAgency() {
        return(agency);
    }
}
